package com.jr.controller;

import com.jr.pojo.Notification;
import com.jr.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/notification")
@CrossOrigin(origins = "*")
public class NotificationController {

    @Autowired
    private NotificationService notificationService;

    @RequestMapping("/send")
    @ResponseBody
    public boolean sendNotification(Notification notification) {
        System.out.println("发送通知");
        return notificationService.sendNotification(notification);
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> getNotificationsByUserId(Integer userId, Integer pageIndex, Integer pageSize) {
        System.out.println("查询通知列表 - userId: " + userId + ", pageIndex: " + pageIndex + ", pageSize: " + pageSize);
        
        // 设置默认值
        if (pageIndex == null || pageIndex < 1) pageIndex = 1;
        if (pageSize == null || pageSize < 1) pageSize = 5;
        
        ArrayList<Notification> notifications = notificationService.getNotificationsByUserIdWithPagination(userId, pageIndex, pageSize);
        int totalCount = notificationService.getNotificationCount(userId);
        int unreadCount = notificationService.getUnreadCount(userId);
        int pageCount = (int) Math.ceil((double) totalCount / pageSize);
        
        Map<String, Object> map = new HashMap<>();
        map.put("notifications", notifications);
        map.put("unreadCount", unreadCount);
        map.put("totalCount", totalCount);
        map.put("pageCount", pageCount);
        map.put("currentPage", pageIndex);
        map.put("pageSize", pageSize);
        return map;
    }

    @RequestMapping("/markRead")
    @ResponseBody
    public boolean markAsRead(Integer notificationId) {
        System.out.println("标记通知为已读");
        return notificationService.markAsRead(notificationId);
    }

    @RequestMapping("/unreadCount")
    @ResponseBody
    public int getUnreadCount(Integer userId) {
        System.out.println("获取未读通知数量");
        return notificationService.getUnreadCount(userId);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public boolean deleteNotification(Integer notificationId) {
        System.out.println("删除通知");
        return notificationService.deleteNotification(notificationId);
    }
}
